#include "Common.h"

#include <stdarg.h>
#include <time.h>

static LOG_LVL_e gLevel = LOG_LVL_DEBUG;

/**********************************************************
 * Function Name:        AppPrint_SetLevel
 * Description:          设置日志打印级别
 * Parameters[in]:       IN LOG_LVL_e level
 * Parameters[out]:      None
 * ReturnValue:          ULONG
 * Author:               liuke
 * Date:                 2024.05.13
***********************************************************/
ULONG AppPrint_SetLevel(IN LOG_LVL_e level)
{
    if (level > LOG_LVL_FATAL || level < LOG_LVL_DEBUG)
    {
        return STAT_ERR_INVAILD_PARAM;
    }

    gLevel = level;

    return STAT_SUCCESS;
}

/**********************************************************
 * Function Name:        AppPrint
 * Description:          日志打印函数，根据日志级别输出带时间戳的格式化日志
 * Parameters[in]:       IN LOG_LVL_e level
 *                       IN const CHAR* format
 *                       ... - 可变参数列表
 * Parameters[out]:      None
 * ReturnValue:          void - 无返回值
 * Author:               liuke
 * Date:                 2024.05.13
 **********************************************************/
void AppPrint(IN LOG_LVL_e level, IN const CHAR* format, ...)
{
    CHAR line[1024] = {0};
    time_t now = 0;
    struct tm timenow = {0};
    va_list argptr;

    if (gLevel > level)
    {
        return;
    }

    time(&now);
    localtime_r(&now, &timenow);

    timenow.tm_year += 1900;
    timenow.tm_mon += 1;

    snprintf(line, sizeof(line), "[%04d-%02d-%02d %02d:%02d:%02d] ",  
            timenow.tm_year, timenow.tm_mon, timenow.tm_mday, timenow.tm_hour, 
            timenow.tm_min, timenow.tm_sec);

    va_start(argptr, format); 
    vsnprintf(line + strlen(line), sizeof(line) - strlen(line), format, argptr);
    va_end(argptr);

    printf("%s", line);

    return;
}
